/* eslint-disable prettier/prettier */

import { Vector3 } from 'three'
import { camera } from './scene.js'
let canUpdate = true

// 主函数，处理精灵组
const forGroupArray = spriteGroup => {
  if (canUpdate) {
    canUpdate = false

    const visibleSprites = []
    const spriteScreenCoords = []

    // 计算所有精灵的屏幕坐标并标记为可见
    spriteGroup.children.forEach(sprite => {
      const screenCoords = getScreenCoords(sprite)
      sprite.visible = true
      visibleSprites.push(sprite)
      spriteScreenCoords.push(screenCoords)
    })

    // 检查每对精灵是否重叠，并隐藏较远的一个
    for (let i = 0; i < visibleSprites.length; i++) {
      for (let j = i + 1; j < visibleSprites.length; j++) {
        checkAndHideSprites(visibleSprites[i], visibleSprites[j], spriteScreenCoords[i], spriteScreenCoords[j])
      }
    }

    // 定时重新计算
    setTimeout(() => {
      canUpdate = true
    }, 1000)
  }
}

// 获取精灵的屏幕坐标和大小
const getScreenCoords = sprite => {
  const worldVector = new Vector3(sprite.position.x, sprite.position.y, sprite.position.z)
  const standardVector = worldVector.project(camera)
  const winWidth = window.innerWidth
  const winHeight = window.innerHeight
  const halfWidth = winWidth / 2
  const halfHeight = winHeight / 2

  const x = Math.round(standardVector.x * halfWidth + halfWidth)
  const y = Math.round(-standardVector.y * halfHeight + halfHeight) - 30
  const width = 100
  const height = 40

  return { x, y, width, height }
}

// 检查两个精灵是否重叠，并隐藏距离较远的一个
const checkAndHideSprites = (sprite1, sprite2, coords1, coords2) => {
  if (coords1.x + coords1.width > coords2.x && coords2.x + coords2.width > coords1.x && coords1.y + coords1.height > coords2.y && coords2.y + coords2.height > coords1.y) {
    const distance1 = sprite1.position.distanceTo(camera.position)
    const distance2 = sprite2.position.distanceTo(camera.position)

    if (distance1 > distance2) {
      sprite1.visible = false
    } else {
      sprite2.visible = false
    }
  }
}

export { forGroupArray }
